<template>
  <div class="subject-list">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="学科名称">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入学科名称" 
            clearable 
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="学科代码">
          <el-input 
            v-model="searchForm.code" 
            placeholder="请输入学科代码" 
            clearable 
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="激活" value="ACTIVE" />
            <el-option label="禁用" value="INACTIVE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="Search">搜索</el-button>
          <el-button @click="resetSearch" icon="Refresh">重置</el-button>
          <el-button type="success" @click="refreshData" icon="RefreshRight">刷新</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>学科列表</span>
          <el-button type="primary" @click="handleAdd" icon="Plus" v-if="hasPermission('subject:list:create')">添加学科</el-button>
        </div>
      </template>
      
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        v-loading="loading"
        empty-text="暂无数据"
      >
        <el-table-column prop="name" label="学科名称" min-width="120" />
        <el-table-column prop="code" label="学科代码" min-width="120" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'ACTIVE' ? 'success' : 'danger'">
              {{ scope.row.status === 'ACTIVE' ? '激活' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" v-if="hasPermission('subject:list:edit')" @click="handleEdit(scope.row)" icon="Edit">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              v-if="hasPermission('subject:list:delete')"
              @click="handleDelete(scope.row)"
              icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { subjectApi, type Subject } from '@/api/subjects'
import { usePermission } from '@/composables/usePermission'

const { hasPermission } = usePermission()

/**
 * 响应式数据定义
 */
const loading = ref(false)
const tableData = ref<Subject[]>([])

// 搜索表单
const searchForm = ref({
  name: '',
  code: '',
  status: ''
})

// 分页配置
const pagination = ref({
  page: 1,
  size: 10,
  total: 0
})

/**
 * 获取学科列表数据
 */
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.page - 1, // 后端从0开始计数
      size: pagination.value.size,
      name: searchForm.value.name || undefined,
      code: searchForm.value.code || undefined,
      status: searchForm.value.status || undefined
    }
    
    const response = await subjectApi.getSubjects(params)
    tableData.value = response.data.content || []
    pagination.value.total = response.data.totalElements || 0
  } catch (error) {
    console.error('获取学科列表失败:', error)
    ElMessage.error('获取学科列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索处理
 */
const handleSearch = () => {
  pagination.value.page = 1
  fetchData()
}

/**
 * 重置搜索条件
 */
const resetSearch = () => {
  searchForm.value = {
    name: '',
    code: '',
    status: ''
  }
  handleSearch()
}

/**
 * 刷新数据
 */
const refreshData = () => {
  fetchData()
}

/**
 * 分页大小改变处理
 */
const handleSizeChange = () => {
  pagination.value.page = 1
  fetchData()
}

/**
 * 当前页改变处理
 */
const handleCurrentChange = () => {
  fetchData()
}

/**
 * 添加学科
 */
const handleAdd = () => {
  // TODO: 实现添加学科功能
  ElMessage.info('添加学科功能待实现')
}

/**
 * 编辑学科
 */
const handleEdit = (row: Subject) => {
  // TODO: 实现编辑学科功能
  ElMessage.info(`编辑学科: ${row.name}`)
}

/**
 * 删除学科
 */
const handleDelete = async (row: Subject) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学科"${row.name}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await subjectApi.deleteSubject(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除学科失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.subject-list {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>


